package tech.horgee.log.utils;

import cn.hutool.core.util.RandomUtil;
import org.slf4j.MDC;

import java.util.Map;

public class TraceIdUtil {
    public static final String TRACE_ID = "ti";

    public static String getTraceId() {
        String traceId = MDC.get(TRACE_ID);
        return traceId == null ? "" : traceId;
    }

    public static void setTraceId(String traceId) {
        MDC.put(TRACE_ID, traceId);
    }

    public static void remove() {
        MDC.remove(TRACE_ID);
    }

    public static void clear() {
        MDC.clear();
    }

    public static String generateTraceId() {
        return String.format("<%s>", RandomUtil.randomStringUpper(16));
    }

    public static void setTraceIdIfAbsent() {
        if (getTraceId().isEmpty()) {
            setTraceId(generateTraceId());
        }
    }

    public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
        return () -> {
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
            }
            //设置traceId
            setTraceIdIfAbsent();
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
